package com.diy.sigmund.diycommon.spring.filter;

import com.diy.sigmund.diycommon.entity.constant.LogConstant;
import com.diy.sigmund.diycommon.spring.RequestWrapper;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

/**
 * <br>将普通的HttpServletRequest转化为自定义的RequestWrapper
 * <br>https://blog.csdn.net/yaomingyang/article/details/108246334
 *
 * <br>urlPatterns匹配规则
 * <br>1、精确匹配 "/user/星号（*）/hi" 这里的*不是通配符，是精确匹配
 * <br>2、扩展名匹配 以*.开头的字符串被用于扩展名匹配 "*.htm"
 * <br>3、路径匹配 以"/"字符开头，并以"/*"结尾的字符串 "/user/*","/*"
 * <br>4、缺省匹配(默认匹配) "/"
 *
 * @author ylm-sigmund
 * @since 2021/8/16 10:53
 */
// @Order
// @Component
// @WebFilter(filterName = "requestWrapperFilter", urlPatterns = {"/*"})
// 这里注释是因为使用@Bean的方式注入
public class RequestWrapperFilter implements Filter {

    private FilterConfig filterConfig = null;
    private static final Logger log = LoggerFactory.getLogger(RequestWrapperFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        log.info(LogConstant.SPRING_LOG, "RequestWrapperFilter处理 开始");
        ServletRequest requestWrapper = null;

        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = (HttpServletRequest) request;
            // 处理多媒体类型的请求，并使用MultipartRequestWrapper包装请求，包装器作为请求对象传递给目标servlet或JSP
            // if (req.getMethod().equalsIgnoreCase(HttpMethod.POST.name())
            //         && req.getHeader(HeaderConstant.CONTENT_TYPE).contains(MediaType.MULTIPART_FORM_DATA_VALUE)) {
            if (ServletFileUpload.isMultipartContent(req)) {
                // 使用标准实现，可以解决TLog获取参数报错
                req = new StandardMultipartHttpServletRequest(req);
                // request = new DefaultMultipartHttpServletRequest(req);
                log.info("文件上传，包装HttpServletRequest");
            }
            requestWrapper = new RequestWrapper(req);
        }
        chain.doFilter(Objects.isNull(requestWrapper) ? request : requestWrapper, response);
        log.info(LogConstant.SPRING_LOG, "RequestWrapperFilter处理 结束");
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

}
